/*
 * @copyright 2010 Gerald Jacobson
 * @license GNU General Public License
 * 
 * This file is part of My Quick Rules.
 *
 * My Quick Rules is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * My Quick Rules is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with My Quick Rules.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.amphiprion.myquickrules;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.amphiprion.myquickrules.entity.Game;
import org.amphiprion.myquickrules.entity.LocalGame;
import org.amphiprion.myquickrules.entity.Version;
import org.amphiprion.myquickrules.task.AvailableVersionTask;
import org.amphiprion.myquickrules.task.AvailableVersionTask.LoadVersionListener;
import org.amphiprion.myquickrules.task.ImportGameRuleTask;
import org.amphiprion.myquickrules.task.ImportGameRuleTask.ImportRuleListener;
import org.amphiprion.myquickrules.view.MyScrollView;
import org.amphiprion.myquickrules.view.VersionSummaryView;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver.OnScrollChangedListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * @author amphiprion
 * 
 */
public class AvailableVersionList extends Activity implements LoadVersionListener, ImportRuleListener {
	private static final int PAGE_SIZE = 10;
	private MyScrollView scrollView;
	private boolean allLoaded;
	private boolean loading;
	private List<Version> versions;
	private int loadedPage;
	// private Version current;
	private Game game;
	private AvailableVersionTask task;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.version_list);

		game = (Game) getIntent().getSerializableExtra("GAME");

		String title = null;// getResources().getString(R.string.menu_search_version);
		title = game.getName();
		setTitle(title);

		final Rect r = new Rect();
		scrollView = (MyScrollView) findViewById(R.id.scroll_view);
		scrollView.setOnScrollChanged(new OnScrollChangedListener() {
			@Override
			public void onScrollChanged() {
				if (!allLoaded && !loading) {
					LinearLayout ln = (LinearLayout) scrollView.getChildAt(0);
					if (ln.getChildCount() > 3) {
						boolean b = ln.getChildAt(ln.getChildCount() - 3).getLocalVisibleRect(r);
						if (b) {
							loading = true;
							loadNextPage();
						}
					}
				}
			}
		});

		init();
	}

	private void init() {
		loadedPage = 0;
		LinearLayout ln = (LinearLayout) findViewById(R.id.version_list);
		ln.removeAllViews();
		ln.addView(getProgressView());
		if (versions == null) {
			versions = new ArrayList<Version>();
		} else {
			versions.clear();
		}
		loadNextPage();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putSerializable("VERSIONS", (Serializable) versions);
		outState.putInt("PAGE", loadedPage);
		outState.putBoolean("ALL_LOADED", allLoaded);
		outState.putSerializable("FILTER", game);
		outState.putInt("SCROLL_X", scrollView.getScrollX());
		outState.putInt("SCROLL_Y", scrollView.getScrollY());
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		versions = (List<Version>) savedInstanceState.getSerializable("VERSIONS");
		loadedPage = savedInstanceState.getInt("PAGE");
		allLoaded = savedInstanceState.getBoolean("ALL_LOADED");
		game = (Game) savedInstanceState.getSerializable("FILTER");
		buildList();
		final int x = savedInstanceState.getInt("SCROLL_X");
		final int y = savedInstanceState.getInt("SCROLL_Y");
		scrollView.post(new Runnable() {
			@Override
			public void run() {
				scrollView.scrollTo(x, y);
			}
		});
	}

	private void loadNextPage() {
		// if (query != null && query.length() > 0) {
		task = new AvailableVersionTask(this, game.getId());
		task.execute();
		// } else {
		// importEnded(true, null);
		// }
	}

	@Override
	protected void onDestroy() {
		if (task != null) {
			task.cancel(true);
		}
		super.onDestroy();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void importEnded(boolean succeed, List<Version> newVersions) {
		if (succeed) {
			task = null;
			if (newVersions != null && newVersions.size() > 0) {
				if (newVersions.size() == PAGE_SIZE) {
					allLoaded = false;
				} else {
					allLoaded = true;
				}
			} else {
				allLoaded = true;
			}
			if (loadedPage != 0) {
				addElementToList(newVersions);
			} else {
				versions = newVersions;
				buildList();
			}
			loadedPage++;
		}
		loading = false;
	}

	private void buildList() {

		LinearLayout ln = (LinearLayout) findViewById(R.id.version_list);
		ln.removeAllViews();
		if (versions != null && versions.size() > 0) {
			addElementToList(versions);
		} else {
			TextView tv = new TextView(this);
			tv.setText(R.string.empty_game_list);
			ln.addView(tv);
		}
	}

	private void addElementToList(List<Version> newVersions) {
		LinearLayout ln = (LinearLayout) findViewById(R.id.version_list);
		if (newVersions != versions) {
			versions.addAll(newVersions);
			if (ln.getChildCount() > 0) {
				ln.removeViewAt(ln.getChildCount() - 1);
			}
		}
		for (final Version version : newVersions) {
			VersionSummaryView view = new VersionSummaryView(this, version);
			view.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					LocalGame lg = new LocalGame();
					lg.setId(version.id);
					lg.setName(game.getName());
					lg.version = version.version;
					lg.resolution = version.resolution;
					lg.length = version.length;
					lg.creator = version.creator;
					lg.mail = version.mail;
					ImportGameRuleTask impTask = new ImportGameRuleTask(AvailableVersionList.this, lg);
					impTask.execute();
				}
			});
			view.setOnLongClickListener(new View.OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					registerForContextMenu(v);
					openContextMenu(v);
					unregisterForContextMenu(v);
					return true;
				}
			});

			ln.addView(view);
		}

		if (!allLoaded) {
			ln.addView(getProgressView());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.amphiprion.myquickrules.task.ImportGameRuleTask.ImportRuleListener
	 * #importEnded(boolean)
	 */
	@Override
	public void importEnded(boolean succeed, LocalGame newGame) {
		if (succeed) {
			setResult(RESULT_OK);
			finish();
		}
	}

	private View getProgressView() {
		LinearLayout lnExpand = new LinearLayout(this);
		LayoutParams lp = new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		lnExpand.setLayoutParams(lp);
		lnExpand.setBackgroundColor(getResources().getColor(android.R.color.black));

		ProgressBar im = new ProgressBar(this);
		LayoutParams imglp = new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		imglp.gravity = Gravity.CENTER_VERTICAL;
		imglp.rightMargin = 5;
		im.setLayoutParams(imglp);
		lnExpand.addView(im);

		TextView tv = new TextView(this);
		tv.setText(getResources().getText(R.string.loading));
		tv.setTextColor(getContext().getResources().getColor(android.R.color.white));
		LayoutParams tlp = new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, 1);
		tlp.gravity = Gravity.CENTER_VERTICAL;

		tv.setLayoutParams(tlp);
		lnExpand.addView(tv);

		return lnExpand;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		menu.clear();
		// if (v instanceof GameSummaryView) {
		// current = ((GameSummaryView) v).getGame();
		// menu.add(1, ApplicationConstants.MENU_ID_VIEW_GAME_TRICTRAC, 0,
		// R.string.goto_trictrac_name);
		// menu.add(1, ApplicationConstants.MENU_ID_VIEW_ADVICES_TRICTRAC, 1,
		// R.string.goto_trictrac_advices);
		// menu.add(2, ApplicationConstants.MENU_ID_CREATE_PARTY, 2,
		// R.string.add_party);
		// menu.add(2, ApplicationConstants.MENU_ID_VIEW_PARTIES, 3,
		// R.string.view_parties);
		// }
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Context getContext() {
		return this;
	}

}
